from PyKrigeHDY.funcMain.ModelMain import gisModeMain
from PyKrigeHDY.funcMain.TifToCustomMesh import tifToCustomMesh
import json,os
from PyKrigeHDY import config
from psutil import net_if_addrs

# flask主程序
from gevent import pywsgi
from flask import Flask, request, make_response, render_template, abort
from PyKrigeHDY.config.macConfig import MAC_ID_LIST
from PyKrigeHDY.config.config import exePort,fileOutDir,fileOutDir1,fileOutDir2,fileOutDir3,demDir

import logging
from logging.handlers import RotatingFileHandler

'''
确定输入输出文件
'''
if not os.path.exists(fileOutDir):
    os.makedirs(fileOutDir)
    print("创建模型文件输出文件夹："+fileOutDir)
if not os.path.exists(fileOutDir+"logs"):
    os.makedirs(fileOutDir+"logs")
    print("创建log日志输出文件夹："+fileOutDir+"logs")
if not os.path.exists(demDir):
    os.makedirs(demDir)
    print("创建栅格输入文件夹："+demDir)

'''
日志输入输出
'''
# 设置日志的记录等级
logging.basicConfig(level=logging.WARNING) # 调试debug级
# 创建日志记录器，指明日志保存的路径（前面的logs为文件的名字，需要我们手动创建，后面则会自动创建）、每个日志文件的最大大小、保存的日志文件个数上限。
# file_log_handler = RotatingFileHandler("../logs/log", maxBytes=1024*1024*100, backupCount=10)
file_log_handler = RotatingFileHandler(fileOutDir+"/logs/log.txt", maxBytes=1024*1024*2, backupCount=10)
# 创建日志记录的格式               日志等级    输入日志信息的文件名   行数       日志信息
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
# 为刚创建的日志记录器设置日志记录格式
file_log_handler.setFormatter(formatter)
# 为全局的日志工具对象（flask app使用的）添加日志记录器
logging.getLogger().addHandler(file_log_handler)


app = Flask(__name__)

os.environ["CUDA_VISIBLE_DEVICES"] = "0"
MacCheck = 0
for k, v in net_if_addrs().items():
    for item in v:
        MacId = item[1]
        if '-' in MacId and len(MacId) == 17:
            for i in MAC_ID_LIST:
                if MacId == i:
                    MacCheck = 1
                    print("———————— 已校验MAC地址 ————————")
                    break

if MacCheck == 0:
    print('此电脑没有运行本程序权限')
else:
    @app.route('/', methods=['GET'])
    def hello_world():
        return 'hello world'


    # 内涝淹没方案
    @app.route('/scheme', methods=['POST'])
    def scheme():
        # print(time.time())
        if (request.content_type == 'application/json'):
            demPath = request.json['demPath']
            demPathFileName = request.json['demPathFileName']
            lon = request.json['lon']
            lat = request.json['lat']
            z = request.json['z']
            schemaName = request.json['schemaName']
        else:
            demPath = request.form['demPath']
            demPathFileName = request.form['demPathFileName']
            lon = request.form.getlist('lon')
            lat = request.form.getlist('lat')
            z = request.form.getlist('z')
            schemaName = request.json['schemaName']
        res = gisModeMain(demPath, demPathFileName, lon, lat, z,schemaName)
        return res


    @app.route('/getSubmergedMesh', methods=['POST'])
    def getSubmergedMesh():
        if (request.content_type == 'application/json'):
            schemeTifName = config.fileOutDir + request.json['schemeTifName']+"Original/" + request.json['schemeTifName'] + "Original.tif"
            schemeTifName1 = config.fileOutDir1 + request.json['schemeTifName'] + "Original/" + request.json[
                'schemeTifName'] + "Original.tif"
            schemeTifName2 = config.fileOutDir2 + request.json['schemeTifName'] + "Original/" + request.json[
                'schemeTifName'] + "Original.tif"
            schemeTifName3 = config.fileOutDir3 + request.json['schemeTifName'] + "Original/" + request.json[
                'schemeTifName'] + "Original.tif"
            centerLon = request.json['centerLon']
            centerLat = request.json['centerLat']
            cellSize = request.json['cellSize']
            if int(cellSize)>300:
                tifToCustomMeshRes = {"msg": "请求的cellSize大于300影响效率!"}
                responseData = json.dumps(tifToCustomMeshRes, ensure_ascii=False)
                response = make_response(responseData)
                response.headers['Accept-Ranges'] = 'bytes'
                response.headers['Access-Control-Allow-Origin'] = '*'
                response.headers['Content-Type'] = 'application/json'
                return response
        else:
            schemeTifName = config.fileOutDir + request.json['schemeTifName']+"Original/"+ request.form['schemeTifName'] + "Original.tif"
            centerLon = request.form['centerLon']
            centerLat = request.form['centerLat']
            cellSize = request.form['cellSize']
            if int(cellSize)>300:
                tifToCustomMeshRes = {"msg": "请求的cellSize大于300影响效率！"}
                responseData = json.dumps(tifToCustomMeshRes, ensure_ascii=False)
                response = make_response(responseData)
                response.headers['Accept-Ranges'] = 'bytes'
                response.headers['Access-Control-Allow-Origin'] = '*'
                response.headers['Content-Type'] = 'application/json'
                return response
        if not os.path.exists(schemeTifName):
            if not os.path.exists(schemeTifName1):
                if not os.path.exists(schemeTifName2):
                    if not os.path.exists(schemeTifName3):
                        tifToCustomMeshRes = {"msg": "no scheme tiff!"}
                        responseData = json.dumps(tifToCustomMeshRes, ensure_ascii=False)
                        response = make_response(responseData)
                        response.headers['Accept-Ranges'] = 'bytes'
                        response.headers['Access-Control-Allow-Origin'] = '*'
                        response.headers['Content-Type'] = 'application/json'
                        return response
                    else:
                        schemeTifName = schemeTifName3;
                else:
                    schemeTifName = schemeTifName2;
            else:
                schemeTifName=schemeTifName1;
        tifToCustomMeshRes = tifToCustomMesh(schemeTifName, centerLon, centerLat, cellSize)
        responseData = json.dumps(tifToCustomMeshRes, ensure_ascii=False)
        response = make_response(responseData)
        response.headers['Accept-Ranges'] = 'bytes'
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Content-Type'] = 'application/json'
        return response


    @app.route('/register', methods=['POST'])
    def register():
        print(request.headers)
        # print(request.stream.read()) # 不要用，否则下面的form取不到数据
        print(request.form)
        print(request.form['lon'])
        print(request.form.get('lon'))
        print(request.form.getlist('lon'))
        print(request.form.get('nickname', default='little apple'))
        return 'welcome'


    if __name__ == '__main__':
        # app.run(debug=False, host='0.0.0.0', port=8088, processes=4)
        app.run(debug=False, host='0.0.0.0', port=exePort, threaded=False)
        # # pywsgi
        # server = pywsgi.WSGIServer(('0.0.0.0', 8088), app)
        # server.multithread=True
        # server.multiprocess=True
        # server.serve_forever()

